<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="applyId">
              <el-input v-model="searchForm.applyId" clearable placeholder="采样编号"></el-input>
            </el-form-item>
            <el-form-item prop="applyUserId">
              <el-input v-model="searchForm.applyUserId" clearable placeholder="用户编号"></el-input>
            </el-form-item>
            <HospitalSelect ref="HospitalSelect" @hospitalId="getHospitalId" :site="2"></HospitalSelect>
            <el-form-item prop="officeId">
              <el-select v-model="searchForm.officeId" @change="listDoctor" filterable :clearable="true" placeholder="科室名称">
                <el-option v-for="item in officeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="doctorId">
              <el-select v-model="searchForm.doctorId" filterable :clearable="true" placeholder="医生名称">
                <el-option v-for="item in doctorList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="areaIds">
              <Region :areaValues="searchForm.areaIds" :isChangeOnSelect="true" @regionChange="handleRegionChange"></Region>
            </el-form-item>
            <el-form-item prop="sampleType">
              <el-select v-model="searchForm.sampleType" :clearable="true" placeholder="请选择采样类型">
                <el-option v-for="item in sampleTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="applyState">
              <el-select v-model="searchForm.applyState" :clearable="true" placeholder="请选择采样状态">
                <el-option v-for="item in applyStateList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="payState">
              <el-select v-model="searchForm.payState" :clearable="true" placeholder="请选择支付状态">
                <el-option v-for="item in payStateList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="linkMan">
              <el-input v-model="searchForm.linkMan" clearable placeholder="联系人"></el-input>
            </el-form-item>
            <el-form-item prop="linkPhone">
              <el-input v-model="searchForm.linkPhone" clearable placeholder="联系电话"></el-input>
            </el-form-item>

            <el-form-item prop="sampleCategory">
              <el-select v-model="searchForm.sampleCategory" :clearable="true" placeholder="采样种类">
                <el-option v-for="item in sampleCategoryList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="collectId">
              <el-select v-model="searchForm.collectId" clearable filterable placeholder="绑码员">
                <el-option v-for="item in collectUserList" :key="item.userId" :label="item.userName" :value="item.userId"> </el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="date">
              <el-date-picker
                v-model="searchForm.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="送检开始日期"
                end-placeholder="送检结束日期"
              ></el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSearch">搜索</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="init" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button size="mini" plain type="info" icon="el-icon-folder" v-has="permissionExport" @click="handleClickExport">导出</el-button>
            <el-button size="mini" plain type="success" icon="el-icon-attract" @click="handleBatchBinding" v-has="permissionBinding"> 批量绑定 </el-button>
            <el-button size="mini" plain type="primary" icon="el-icon-data-board" @click="handleBatchSetNotice" v-has="permissionSetNotice">批量设置公告</el-button>
          </div>
          <!--<el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd"
            @click="handleClickAdd()" size="mini"> 新增</el-button>-->
          <!--<span class="line">|</span>-->
          <!--<el-button type="primary" icon="fa fa-mail-forward">导出</el-button>-->
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <el-table :data="tableList" @row-dblclick="handleClickSample" @selection-change="handleBatchBindingChange" :fit="true">
        <!-- <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>-->
        <el-table-column align="center" type="selection" width="55"> </el-table-column>
        <el-table-column prop="applyId" label="采样编号" width="70" align="center"></el-table-column>
        <!-- <el-table-column prop="collageId" label="拼团号" width="70" align="center"></el-table-column> -->
        <el-table-column prop="itemName" label="项目名称" width="140"></el-table-column>
        <el-table-column label="采样类型/种类" width="120" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.sampleType">
              <el-tag size="mini" :type="formatSampleTypes(scope.row.sampleType)">
                {{ formatSampleType(scope.row.sampleType) }}
              </el-tag>
            </span>
            -
            <span v-if="scope.row.sampleCategory">
              <el-tag size="mini" :type="formatSampleCategory(scope.row.sampleCategory)">
                {{ formatSampleCategory(scope.row.sampleCategory) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>

        <!--<el-table-column label="采样种类" width="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.sampleCategory">
              <el-tag
                size="mini"
                :type="formatSampleCategory(scope.row.sampleCategory)"
              >

              </el-tag>
            </span>
          </template>
        </el-table-column>-->

        <el-table-column width="170" label="医院-科室-医生">
          <template slot-scope="scope">
            <span>{{ scope.row.hospitalName }} - {{ scope.row.officeName }} - {{ scope.row.doctorName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="institutionName" label="医检名称" width="120"></el-table-column>
        <el-table-column prop="userNum" label="人员数量" width="70" align="center"></el-table-column>
        <el-table-column prop="itemPrice" label="采样价格" width="70" align="center"></el-table-column>
        <el-table-column prop="applyTime" label="采样时间" width="90"></el-table-column>
        <el-table-column prop="linkMan" label="联系人" width="75"></el-table-column>
        <el-table-column prop="linkPhone" label="联系电话" width="100"></el-table-column>
        <el-table-column prop="address" label="详细地址" width="200"></el-table-column>
        <el-table-column label="采样状态" align="center">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatApplyStateType(scope.row.applyState)">
                {{ formatApplyState(scope.row.applyState) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="90"></el-table-column>
        <!-- <el-table-column label="是否咨询" width="80" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isAsk == 1">
              <el-tag size="mini" type="danger">
                咨询
              </el-tag>
            </span>
          </template>
        </el-table-column> -->
        <el-table-column label="支付状态" align="center">
          <template slot-scope="scope">
            <span>
              <el-tag :type="formatPayStateType(scope.row.payState)" size="mini" effect="plain">
                {{ formatPayState(scope.row.payState) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionTakeAdd" v-if="scope.row.applyState == 2" @click="handleClickSample(scope.row)" size="mini">开始采样</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionCheck" @click.native="handleClickDetail(scope.row)">查看</el-dropdown-item>
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpUser" @click.native="handleClickEditUser(scope.row)">修改用户</el-dropdown-item>
                  <el-dropdown-item v-has="permissionSetNotice" @click.native="setNoticeDialog(scope.row.applyId)">设置公告</el-dropdown-item>
                  <el-dropdown-item v-has="permissionMerchant" @click.native="setMerchantDialog(scope.row.applyId)">设置商户号</el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{ scope.row.state == 0 ? '启用' : '禁用' }}</el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" v-if="scope.row.state == 0" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <el-dialog title="修改用户信息" :visible.sync="hideDialogShow" :center="isCenter" width="900px">
      <el-table :data="sampleUserList" border style="width: 100%">
        <el-table-column property="applyUserId" label="条码号" width="100"></el-table-column>
        <el-table-column property="name" label="姓名">
          <template slot-scope="scope">
            <input v-model="scope.row.name" placeholder="请输入姓名" />
          </template>
        </el-table-column>
        <el-table-column property="idCard" label="身份证">
          <template slot-scope="scope">
            <input v-model="scope.row.idCard" placeholder="请输入身份证" />
          </template>
        </el-table-column>
        <el-table-column property="sampleState" :formatter="formatSampleState" width="100" label="采样状态"> </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-row>
              <el-button @click="updateSampleUser(scope.row)" size="mini">保存</el-button>
              <el-button @click="deleteSampleUser(scope.row)" size="mini">删除</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 设置公告 -->
    <el-dialog :visible.sync="noticeVisible" :title="showClear ? '设置公告' : '批量设置公告'" width="500px" center>
      <div style="position: relative">
        <el-button v-show="showClear" class="clear" type="danger" circle plain @click="confirmSetNotice(0)">清除</el-button>
        <el-input clearable type="textarea" v-model="noticeContent" rows="7"></el-input>
      </div>
      <template slot="footer">
        <el-button @click.native="noticeVisible = false"> 取消 </el-button>
        <el-button type="primary" @click.native="confirmSetNotice"> 确定 </el-button>
      </template>
    </el-dialog>

    <!-- 设置商户号 -->
    <el-dialog :visible.sync="merchantVisible" title="设置商户号" center width="400px">
      <div style="text-align: center">
        <el-select v-model="merchantId" placeholder="请选择商户号" filterable>
          <el-option v-for="item in merchantList" :label="item.label" :value="item.value" :key="item.value"> </el-option>
        </el-select>
      </div>
      <template slot="footer">
        <el-button @click.native="merchantVisible = false"> 取消 </el-button>
        <el-button type="primary" @click.native="confirmSetMerchant"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import SampleApplyApi from '@/api/sample/sampleApply';
import MerchantNoApi from '@/api/finance/merchantNo';
import HospitalSelect from '@/components/HospitalSelect';
import Region from '@/components/Region';
import OfficeApi from '@/api/institution/office';
import DoctorApi from '@/api/institution/doctor';
import AuthApi from '@/api/system/auth';
import { getStorage } from '@/utils/auth';
import * as stn from '@/constants/storeName';

export default {
  name: 'SampleApplyManagement', // 缓存当前页面，需要给当前页面命名，并且在路由meta加上cache:true
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      tableList: [],
      sampleUserList: [],
      hospitalNameList: [],
      officeList: [],
      doctorList: [],
      // 绑码员列表
      collectUserList: [],
      excelData: {},
      hideHospitalForm: {
        institutionId: '',
        hospitalSelIds: [],
        institutionSelName: '',
      },

      // 临时的采样点击某行操作的时候保存下来
      tempApplyId: '',
      // 设置公告
      noticeVisible: false,
      // 是否显示清除
      showClear: '',
      // 批量设置公告选中的ids
      selectIds: [],
      noticeContent: '',
      // 设置商户号
      merchantVisible: false,
      merchantId: '',
      merchantList: [],

      userRole: '',
      hideDialogShow: false,
      isCenter: true,

      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
      },
      searchForm: {
        provinceId: '',
        cityId: '',
        areaId: '',
        areaIds: [],
        linkMan: '',
        linkPhone: '',
        applyId: '',
        applyUserId: '',
        hospitalId: '',
        officeId: '',
        doctorId: '',
        payState: '',
        sampleType: '',
        sampleCategory: '',
        applyState: '',
        // 绑码员Id
        collectId: '',
        date: [],
      },
      bindingApplyIds: [],
      sampleCategoryList: [
        { label: '人', value: 1 },
        { label: '环境', value: 2 },
      ],
      //1.单采 5.混采5人 10.混采10人
      sampleTypeList: [
        { label: '单采', value: 1 },
        { label: '5混采', value: 5 },
        { label: '10混采', value: 10 },
        { label: '20混采', value: 20 },
      ],
      //采样状态：(1.申请中 2.已安排上门 3.已取消 4.已完成)
      applyStateList: [
        { label: '申请中', value: '1' },
        { label: '已安排上门', value: '2' },
        { label: '已取消', value: '3' },
        { label: '已完成', value: '4' },
      ],
      //支付状态：(1.未支付 2.已付订金 3.已付款 4.已退款 5.已取消)
      payStateList: [
        { label: '未支付', value: '1' },
        { label: '已付订金', value: '2' },
        { label: '已付款', value: '3' },
        { label: '已退款', value: '4' },
        { label: '已取消', value: '5' },
      ],
      permissionTakeAdd: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_TAKE_ADD',
      permissionCheck: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_EDIT',
      permissionUpUser: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_UPDATE_USER',
      permissionUpStatus: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_DELETE',
      permissionExport: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_EXPORT',
      permissionBinding: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_BINDING',
      permissionSetNotice: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_SER_NOTICE',
      permissionMerchant: 'SYSTEM_MANAGER_SAMPLE_APPLY_LIST_MERCHANT',
    };
  },
  components: {
    HospitalSelect,
    Region,
  },
  created() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  mounted() {
    // 为了实现手机端下拉框可以打字搜索
    this.$Utils.removeSelectReadOnly();
  },
  //activated,deactivated这两个生命周期函数一定是要在使用了keep-alive组件后才会有的，否则则不存在
  activated() {
    this.init();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      _this.userInfo = getStorage(stn.USER_INFO);
      //_this.initDate();
      _this.getMerchantList();
      _this.getCollectUserList();
      _this.listTable();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },


    //采样类型(1.单采 5.5混采 10.10混采)
    formatSampleType(cellValue) {
      if (cellValue == 1) {
        return '单采';
      } else if (cellValue == 5) {
        return '5混采';
      } else if (cellValue == 10) {
        return '10混采';
      } else if (cellValue == 20) {
        return '20混采';
      }
    },
    formatSampleTypes(cellValue) {
      if (cellValue == 1) {
        return 'success';
      } else if (cellValue == 5) {
        return 'warning';
      } else if (cellValue == 10) {
        return 'danger';
      }
    },
    formatSampleCategory(cellValue) {
      if (cellValue == 1) {
        return '人';
      } else if (cellValue == 2) {
        return '环境';
      }
    },
    //采样状态：(1.申请中 2.已安排上门 3.已取消 4.已完成)
    formatApplyState(cellValue) {
      if (cellValue == 1) {
        return '申请中';
      } else if (cellValue == 2) {
        return '已安排上门';
      } else if (cellValue == 3) {
        return '已取消';
      } else if (cellValue == 4) {
        return '已完成';
      }
    },
    formatApplyStateType(cellValue) {
      if (cellValue == 1) {
        return '';
      } else if (cellValue == 2) {
        return 'success';
      } else if (cellValue == 3) {
        return 'info';
      } else if (cellValue == 4) {
        return 'success';
      }
    },
    //支付状态：(1.未支付 2.已付订金 3.已付款 4.已退款 5.已取消)
    formatPayState(cellValue) {
      if (cellValue == 1) {
        return '未支付';
      } else if (cellValue == 2) {
        return '已付订金';
      } else if (cellValue == 3) {
        return '已付款';
      } else if (cellValue == 4) {
        return '已退款';
      } else if (cellValue == 5) {
        return '已取消';
      }
    },
    formatPayStateType(cellValue) {
      if (cellValue == 1) {
        return 'info';
      } else if (cellValue == 2) {
        return '';
      } else if (cellValue == 3) {
        return 'success';
      } else if (cellValue == 4) {
        return 'warning';
      } else if (cellValue == 5) {
        return 'info';
      }
    },
    formatSampleState(row, column, cellValue) {
      if (cellValue == 1) {
        return '已采';
      } else {
        return '';
      }
    },
    formatState(row, column, cellValue) {
      if (cellValue == -1) {
        return '删除';
      } else if (cellValue == 0) {
        return '禁用';
      } else if (cellValue == 1) {
        return '启用';
      }
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    // 获取绑码员列表
    getCollectUserList() {
      AuthApi.listAllAdmin({}).then((res) => {
        this.collectUserList = res.data;
      });
    },
    getHospitalId(val) {
      let _this = this;
      _this.searchForm.hospitalId = val;
      _this.officeList = [];
      _this.searchForm.officeId = '';
      _this.doctorList = [];
      _this.searchForm.doctorId = '';
      let cond = {
        hospitalId: val,
      };
      OfficeApi.getOfficeNames(cond)
        .then((res) => {
          setTimeout(() => {
            _this.officeList = res.data.map((item) => {
              return {
                value: item.officeId,
                label: item.officeName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.officeList = [];
          console.error(error);
        });
    },
    listDoctor() {
      let _this = this;
      _this.doctorList = [];
      _this.searchForm.doctorId = '';
      let cond = {
        hospitalId: _this.searchForm.hospitalId,
        officeId: _this.searchForm.officeId,
      };
      DoctorApi.getDoctorNames(cond)
        .then((res) => {
          setTimeout(() => {
            _this.doctorList = res.data.map((item) => {
              return {
                value: item.doctorId,
                label: item.doctorName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.doctorList = [];
          console.error(error);
        });
    },
    updateSampleUser(row) {
      let cond = {
        applyUserId: row.applyUserId,
        name: row.name,
        idCard: row.idCard,
      };
      SampleApplyApi.updateSampleApplyUser(cond)
        .then((res) => {
          if (res.status == 0) {
            this.$message.success('修改成功');
          } else {
            this.$message.error('修改失败');
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
    deleteSampleUser(row) {
      let cond = {
        id: row.applyUserId,
        state: -1,
      };
      SampleApplyApi.deleteApply(cond)
        .then((res) => {
          if (res.status == 0) {
            this.$message.success('删除成功');
            this.hideDialogShow = false;
          } else {
            this.$message.error('删除失败');
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    handleClickAdd() {
      this.$router.push('/sample/sampleApplyAdd');
    },
    handleClickEditor(row) {
      this.$router.push({
        path: '/sample/sampleApplyEdit',
        query: { id: row.applyId },
      });
    },
    handleClickEditUser(row) {
      SampleApplyApi.getSampleApplyUserByApplyId({ applyId: row.applyId })
        .then((res) => {
          this.sampleUserList = res.data.list;
        })
        .catch((error) => {
          console.error(error);
        });
      this.hideDialogShow = true;
    },
    handleClickSample(row) {
      this.$router.push({
        path: '/sample/sampleTakeAdd',
        query: { id: row.applyId },
      });
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let deleteFormData = {
          applyId: row.applyId,
          state: -1,
        };
        SampleApplyApi.deleteSampleApply(deleteFormData).then((res) => {
          this.listTable();
          this.$Utils.notifySuccess();
        });
      });
    },
    handleClickDetail(row) {
      this.$router.push({
        path: '/sample/sampleApplyDetail',
        query: { id: row.applyId },
      });
    },
    handleIsDisable(row) {
      let currentState = row.state == 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        let disableFormData = {
          applyId: row.applyId,
          state: currentState,
        };
        SampleApplyApi.deleteSampleApply(disableFormData).then((res) => {
          row.state = currentState;
          this.$Utils.notifySuccess();
        });
      });
    },
    // 用户点击导出
    handleClickExport() {
      let _this = this;
      this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 导出前先刷新项目
          _this.init();
          let cond = {
            applyId: this.searchForm.applyId,
            hospitalId: this.searchForm.hospitalId,
            cityId: this.searchForm.cityId,
            areaId: this.searchForm.areaId,
            linkMan: this.searchForm.linkMan,
            linkPhone: this.searchForm.linkPhone,
            sampleCategory: this.searchForm.sampleCategory,
            sampleType: this.searchForm.sampleType,
            provinceId: this.searchForm.provinceId,
            payState: this.searchForm.payState,
            officeId: this.searchForm.officeId,
            doctorId: this.searchForm.doctorId,
            applyState: this.searchForm.applyState,
          };
          if (this.searchForm.date && this.searchForm.date.length == 2) {
            cond.startSampleDate = this.$Utils.formatDate(this.searchForm.date[0], 'yyyy-MM-dd hh:mm:ss');
            cond.endSampleDate = this.$Utils.formatDate(this.searchForm.date[1], 'yyyy-MM-dd hh:mm:ss');
          }
          SampleApplyApi.getSampleExport(cond).then((res) => {
            if (res.data && res.data.length > 0) {
              let result = res.data;
              result.forEach((item) => {
                if (item.isAsk == 1) {
                  item.isAsk = '咨询';
                }
                if (item.sampleType) {
                  item.sampleType = this.formatSampleType(item.sampleType);
                }
                item.applyState = this.formatApplyState(item.applyState);
                item.payState = this.formatPayState(item.payState);
              });
              _this.excelData = result;
              this.export2Excel();
            } else {
              this.$notify.error({
                title: message.TITLE_ERROR,
                message: '未找到可导出的数据，请重新查询',
              });
            }
          });
        })
        .catch(() => {
          console.error(error);
        });
    },
    // 批量绑定
    handleBatchBindingChange(val) {
      // 这里bindingApplyIds与selectIds实际上是一个东西可以合在一起
      this.bindingApplyIds = val.map((item) => item.applyId);
      this.selectIds = val.map((item) => item.applyId);
    },
    // 用户点击批量绑定
    handleBatchBinding() {
      if (this.bindingApplyIds.length == 0) {
        this.$message.error({
          message: '请至少选择一项',
        });
        return;
      }
      this.$confirm('确认提交绑定吗？', '提示', {
        confirmTextButton: '确认',
        cancelTextButton: '取消',
      }).then(() => {
        let params = {
          groupApplyIds: this.bindingApplyIds.join(','),
        };
        SampleApplyApi.batchBinding(params).then((res) => {
          this.listTable();
        });
      });
    },
    export2Excel() {
      let that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel'); //这里必须使用绝对路径 拼团号 collageId
        const tHeader = [
          '采样编号',
          '项目名称',
          '采样类型',
          '医院',
          '科室',
          '医生',
          '医检名称',
          '人员数量',
          '采样种类',
          '采样价格',
          '采样时间',
          '绑码员',
          '收样员',
          '采样状态',
          '支付状态',
          '联系人',
          '联系电话',
          '详细地址',
          '创建人',
          '创建时间',
          '修改人',
          '修改时间',
        ]; // 导出的表头名
        const filterVal = [
          'applyId',
          'itemName',
          'sampleType',
          'hospitalName',
          'officeName',
          'doctorName',
          'institutionName',
          'userNum',
          'sampleCategory',
          'itemPrice',
          'applyTime',
          'collectNames',
          'syUserNames',
          'applyState',
          'payState',
          'linkMan',
          'linkPhone',
          'address',
          'createUserName',
          'createDate',
          'modifyUserName',
          'modifyDate',
        ]; // 导出的表头字段名
        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        //let time1,time2 = '';
        //export_json_to_excel(tHeader, data, `[${time1}-${time2}]医生管理列表`);// 导出的表格名称，根据需要自己命名
        let currentTime = this.$Utils.formatDate(new Date(), 'yyyy-MM-dd');
        export_json_to_excel(tHeader, data, `康来采样预约数据_${currentTime}`); // 导出的表格名称，根据需要自己命名
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    handleRegionChange(val) {
      this.searchForm.provinceId = val.provinceId;
      this.searchForm.cityId = val.cityId;
      this.searchForm.areaId = val.areaId;
      this.searchForm.areaIds = [val.provinceId, val.cityId, val.areaId];
    },
    // 设置公告
    setNoticeDialog(id) {
      let params = {
        applyId: id,
      };
      SampleApplyApi.getNotice(params).then((res) => {
        this.tempApplyId = id;
        this.noticeContent = res.data;
        this.showClear = true;
        this.noticeVisible = true;
      });
    },
    // 批量设置公告
    handleBatchSetNotice() {
      if (this.selectIds.length == 0) {
        this.$message.error('请至少选择一项！');
        return;
      }
      this.showClear = false;
      this.noticeVisible = true;
      this.noticeContent = '';
      this.tempApplyId = this.selectIds;
    },

    confirmSetNotice(type = 1) {
      // this.noticeVisible =  true
      let params = {
        [Array.isArray(this.tempApplyId) ? 'ids' : 'id']: this.tempApplyId,
        content: type ? this.noticeContent : '',
      };
      let tip = type ? '确认提交修改吗？' : '确认清除公告吗？';
      this.$confirm(tip, '提示', {}).then((res) => {
        SampleApplyApi.setNotice(params).then((res) => {
          this.$message.success('操作成功');
          this.noticeVisible = false;
          this.listTable();
        });
      });
    },

    // 获取商户号列表
    getMerchantList() {
      MerchantNoApi.listMchNoIdName().then((res) => {
        if (res.data.length > 0) {
          this.merchantList = res.data.map((item) => {
            return {
              value: item.id,
              label: item.name,
            };
          });
        } else {
          this.merchantList = [];
        }
      });
    },
    // 设置商户号弹框
    setMerchantDialog(id) {
      SampleApplyApi.getSampleApplyMch({ applyId: id }).then((res) => {
        this.tempApplyId = id;
        this.merchantVisible = true;
        this.merchantId = res.data;
      });
    },
    confirmSetMerchant() {
      this.$confirm('确定设置商户号吗？', '提示', {}).then((res) => {
        let parmas = {
          applyId: this.tempApplyId,
          mchInfoId: this.merchantId,
        };
        SampleApplyApi.setSampleApplyMch(parmas).then((res) => {
          this.$message.success('操作成功');
          this.merchantVisible = false;
          this.listTable();
        });
      });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.$refs.HospitalSelect.hospitalIdEmpty();
      //this.initDate();
      this.searchForm.provinceId = '';
      this.searchForm.cityId = '';
      this.searchForm.areaId = '';
      this.onSearch();
    },
    // initDate(){
    //   let begin = new Date();
    //   begin.setHours(0);
    //   begin.setMinutes(0);
    //   begin.setSeconds(0);
    //   begin.setMonth(begin.getMonth()-1);
    //   let end = new Date();
    //   end.setHours(23);
    //   end.setMinutes(59);
    //   end.setSeconds(59);
    //   this.searchForm.date = [begin,end];
    // },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        hospitalId: this.searchForm.hospitalId,
        officeId: this.searchForm.officeId,
        doctorId: this.searchForm.doctorId,
        linkMan: this.searchForm.linkMan,
        linkPhone: this.searchForm.linkPhone,
        sampleCategory: this.searchForm.sampleCategory,
        applyId: this.searchForm.applyId,
        applyUserId: this.searchForm.applyUserId,
        provinceId: this.searchForm.provinceId,
        cityId: this.searchForm.cityId,
        areaId: this.searchForm.areaId,
        sampleType: this.searchForm.sampleType,
        payState: this.searchForm.payState,
        applyState: this.searchForm.applyState,
        collectId: this.searchForm.collectId,
      };
      if (this.searchForm.date && this.searchForm.date.length == 2) {
        data.startSampleDate = this.$Utils.formatDate(this.searchForm.date[0], 'yyyy-MM-dd hh:mm:ss');
        data.endSampleDate = this.$Utils.formatDate(this.searchForm.date[1], 'yyyy-MM-dd hh:mm:ss');
      }
      SampleApplyApi.listSampleApply(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
<style lang="scss" scoped>
.clear {
  position: absolute;
  z-index: 999;
  top: -65px;
  width: 35px;
  height: 35px;
  padding: 3px;
  font-size: 13px !important;
}
</style>
